package legato.injection
{
	import flash.utils.describeType;
	
	public class MetaInjecter
	{
		public static const META_NAME:String = "Inject";
		
		public static function configure(component:Object, context:String = null):void
		{
			var descr:XML = describeType(component);
			var allVars:XMLList = descr.children().(name() == "variable" || name() == "accessor");
			for(var i:int = 0; i < allVars.length(); i++)
			{
				
				var testVar:XML = allVars[i];
				if (testVar.metadata != null && testVar.metadata.(@name == META_NAME).length() > 0)
				{
					var varName:String = testVar.@name;
					var injectionMetadata:XML = testVar.metadata.(@name == META_NAME)[0];
					
					var injectId:String = injectionMetadata.arg.(@key=="id").@value;
					if (injectId == null || injectId == "")
					{
						injectId = injectionMetadata.arg.(@key=="").@value;
					}
					var injectType:String = injectionMetadata.arg.(@key=="type").@value;

					if (injectId != null && injectId.length > 0)
					{
						injectByName(component,varName,injectId, context);
					}
					else if (injectType != null && injectType.length > 0)
					{
						injectByType(component,varName,injectType, context);
					}
					else
					{
						//Try to inject by variable type
						injectType = testVar.@type;
						injectByType(component,varName,injectType, context);
					}
					
				}
			}
		} 
		
		
		private static function injectByName(component:Object, property:String, componentName:String, context:String):void
		{
			component[property] = DILocator.getContainer().getComponentById(componentName,context);
		}
		
		private static function injectByType(component:Object, property:String, componentType:String, context:String):void
		{
			component[property] = DILocator.getContainer().getComponentByInterface(componentType,context);
		}


	}
}  